Switch Case คือ คำสั่งสำหรับการสร้างเงื่อนไขแบบทำหลายทิศทาง ซึ่งจะไม่เหมือนกับ If - Then - Else Statement เพราะ Switch Statement นั้นจะสามารถทำได้หลายเงื่อนไขที่เป็นจริง ซึ่งสามารถทำงานกับชนิดข้อมูลต่าง ๆ เช่น byte, short, char, และ int primitive data types อีกทั้งยังทำงานรวมกับชนิดข้อมูล enumerated ได้อีกด้วย (ไม่ขอกล่าวถึง enumerated ในบทความนี้ครับ)
ภาพรวมของ Switch Statement
1. ประกอบไปด้วย 3 คำสั่งหลัก ๆ คือ switch, case และ break
2. switch ใช้สำหรับระบุค่าที่ต้องการสร้างเงื่อนไข
3. case ใช้สำหรับระบุขั้นตอนการดำเนินงานในแต่ละทิศทาง
4. break ใช้สำหรับจบขั้นตอนการดำเนินงานในเหตุการณ์นั้น ๆ
5. ใช้คำสั่ง default เพื่อระบุถึงขั้นตอนการดำเนินงานที่ไม่พบทิศทางใด ๆ
ตัวอย่างโปรแกรม
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class SwitchCase {
public static void main(String args[]){
int score = 3 ;
switch ( score ) {
case 5 : System.out.println( "Score : " + score + " = A" ); break ;
case 4 : System.out.println( "Score : " + score + " = B" ); break ;
case 3 : System.out.println( "Score : " + score + " = C" ); break ;
case 2 : System.out.println( "Score : " + score + " = D" ); break ;
case 1 : System.out.println( "Score : " + score + " = E" ); break ;
default : System.out.println( "Score : " + score + " = F" );
}
}
}
|
ผลลัพธ์
